package com.outdoor.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.outdoor.model.dto.response.ApiResponse;
import com.outdoor.model.dto.response.TripResponse;
import com.outdoor.model.entity.Trip;
import com.outdoor.model.entity.User;
import com.outdoor.model.enums.ActivityType;
import com.outdoor.model.enums.TripStatus;
import com.outdoor.service.TripService;
import com.outdoor.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 行程控制器
 * 
 * @author OutdoorTeam
 * @date 2025-05-18
 */
@Slf4j
@RestController
@RequestMapping("/api/trips")
@RequiredArgsConstructor
@Tag(name = "行程管理", description = "行程相关接口")
public class TripController {

    private final TripService tripService;
    private final UserService userService;

    @PostMapping
    @Operation(summary = "创建行程", description = "创建新行程")
    public ApiResponse<TripResponse> createTrip(@Valid @RequestBody Trip tripRequest) {
        // 模拟获取当前用户ID
        Long currentUserId = 1L;
        log.debug("创建行程请求: {}", tripRequest.getName());
        
        Trip trip = tripService.createTrip(tripRequest, currentUserId);
        User organizer = userService.getUserById(trip.getOrganizerId());
        return ApiResponse.success("行程创建成功", 
            TripResponse.fromEntityWithDetails(trip, organizer.getName(), 0));
    }

    @PostMapping("/from-team/{teamId}")
    @Operation(summary = "从团队创建行程", description = "根据团队信息创建行程")
    public ApiResponse<TripResponse> createTripFromTeam(@PathVariable Long teamId) {
        // 模拟获取当前用户ID
        Long currentUserId = 1L;
        log.debug("从团队创建行程请求: 团队ID={}", teamId);
        
        Trip trip = tripService.createTripFromTeam(teamId, currentUserId);
        User organizer = userService.getUserById(trip.getOrganizerId());
        return ApiResponse.success("从团队创建行程成功", 
            TripResponse.fromEntityWithDetails(trip, organizer.getName(), 0));
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取行程", description = "根据ID获取行程信息")
    public ApiResponse<TripResponse> getTripById(@PathVariable Long id) {
        log.debug("获取行程请求: ID={}", id);
        Trip trip = tripService.getTripById(id);
        User organizer = userService.getUserById(trip.getOrganizerId());
        // 实际项目中需要查询成员数量
        return ApiResponse.success(TripResponse.fromEntityWithDetails(trip, organizer.getName(), 0));
    }

    @GetMapping("/team/{teamId}")
    @Operation(summary = "获取团队行程", description = "获取团队相关的行程")
    public ApiResponse<List<TripResponse>> getTripsByTeamId(@PathVariable Long teamId) {
        log.debug("获取团队行程请求: 团队ID={}", teamId);
        
        List<Trip> trips = tripService.getTripsByTeamId(teamId);
        
        // 为每个行程补充组织者名称
        List<TripResponse> responses = trips.stream()
            .map(trip -> {
                User organizer = userService.getUserById(trip.getOrganizerId());
                return TripResponse.fromEntityWithDetails(trip, organizer.getName(), 0);
            })
            .collect(Collectors.toList());
            
        return ApiResponse.success(responses);
    }

    @PutMapping("/{id}/status")
    @Operation(summary = "更新行程状态", description = "更新行程状态")
    public ApiResponse<TripResponse> updateTripStatus(@PathVariable Long id, @RequestParam TripStatus status) {
        // 模拟获取当前用户ID
        Long currentUserId = 1L;
        log.debug("更新行程状态请求: ID={}, 状态={}", id, status);
        
        Trip trip = tripService.updateTripStatus(id, status, currentUserId);
        User organizer = userService.getUserById(trip.getOrganizerId());
        return ApiResponse.success("行程状态更新成功", 
            TripResponse.fromEntityWithDetails(trip, organizer.getName(), 0));
    }

    @PostMapping("/{id}/photos")
    @Operation(summary = "添加行程照片", description = "为行程添加照片")
    public ApiResponse<TripResponse> addTripPhoto(@PathVariable Long id, @RequestParam String photoUrl) {
        // 模拟获取当前用户ID
        Long currentUserId = 1L;
        log.debug("添加行程照片请求: ID={}, 照片URL={}", id, photoUrl);
        
        Trip trip = tripService.addTripPhoto(id, photoUrl, currentUserId);
        User organizer = userService.getUserById(trip.getOrganizerId());
        return ApiResponse.success("照片添加成功", 
            TripResponse.fromEntityWithDetails(trip, organizer.getName(), 0));
    }

    @GetMapping("/organizer/{userId}")
    @Operation(summary = "获取用户组织的行程", description = "获取指定用户组织的行程列表")
    public ApiResponse<IPage<TripResponse>> getTripsByOrganizer(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        log.debug("获取用户组织的行程请求: 用户ID={}", userId);
        
        Page<Trip> page = new Page<>(current, size);
        IPage<Trip> trips = tripService.getTripsByOrganizer(userId, page);
        
        // 查询组织者信息
        User organizer = userService.getUserById(userId);
        
        IPage<TripResponse> responseIPage = trips.convert(trip -> 
            TripResponse.fromEntityWithDetails(trip, organizer.getName(), 0));
        return ApiResponse.success(responseIPage);
    }

    @GetMapping("/status/{status}")
    @Operation(summary = "按状态获取行程", description = "获取指定状态的行程列表")
    public ApiResponse<IPage<TripResponse>> getTripsByStatus(
            @PathVariable TripStatus status,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        log.debug("按状态获取行程请求: 状态={}", status);
        
        Page<Trip> page = new Page<>(current, size);
        IPage<Trip> trips = tripService.getTripsByStatus(status, page);
        
        IPage<TripResponse> responseIPage = trips.convert(trip -> {
            User organizer = userService.getUserById(trip.getOrganizerId());
            return TripResponse.fromEntityWithDetails(trip, organizer.getName(), 0);
        });
        return ApiResponse.success(responseIPage);
    }

    @GetMapping("/filter")
    @Operation(summary = "筛选行程", description = "根据活动类型和状态筛选行程")
    public ApiResponse<IPage<TripResponse>> getTripsByActivityTypeAndStatus(
            @RequestParam ActivityType activityType,
            @RequestParam TripStatus status,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        
        log.debug("筛选行程请求: 活动类型={}, 状态={}", activityType, status);
        
        Page<Trip> page = new Page<>(current, size);
        IPage<Trip> trips = tripService.getTripsByActivityTypeAndStatus(activityType, status, page);
        
        IPage<TripResponse> responseIPage = trips.convert(trip -> {
            User organizer = userService.getUserById(trip.getOrganizerId());
            return TripResponse.fromEntityWithDetails(trip, organizer.getName(), 0);
        });
        return ApiResponse.success(responseIPage);
    }
}